import Koa from 'koa'
import R from 'ramda'
import { resolve } from 'path'

const r = path => resolve(__dirname, path)
const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 80
const MIDDLEWARE = ['database', 'router']

class Server {
  constructor () {
    this.app = new Koa()
    this.useMiddlewares(this.app)(MIDDLEWARE) 
  }
  useMiddlewares (app) {
    return R.map(R.compose(
      R.map(i => i(app)),
      require,
      i => `${r('./middleware')}/${i}`)
    )
  }
  async start () {
    this.app.use(async (ctx, next) => {
      await next()
      ctx.status = 200 // koa defaults to 404 when it sees that status is unset
      return new Promise((resolve, reject) => {
        ctx.res.on('close', resolve)
        ctx.res.on('finish', resolve)
      })
    })
    this.app.listen(port, host)
    console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
  }
}
const app = new Server()
app.start()
